﻿//
// © Algobox Ltd - Benn Eichhorn
//
using System;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace Algobox.Toolbox.Collections
{
    public class ConcurrentObservableCollection<T> : ObservableCollection<T>
    {
        #region Member Variables

        public override event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged;

        #endregion

        //////////

        #region Functions

        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            using (BlockReentrancy())
            {
                System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;

                if (eventHandler == null)
                    return;

                Delegate[] delegates = eventHandler.GetInvocationList();

                foreach (System.Collections.Specialized.NotifyCollectionChangedEventHandler handler in delegates)
                {
                    DispatcherObject dispatcherObject = handler.Target as DispatcherObject;

                    // check non UI thread
                    if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
                    {
                        dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);
                        //dispatcherObject.Dispatcher.Invoke(handler, TimeSpan.FromSeconds(10), DispatcherPriority.DataBind, e);
                    }
                    else
                    {
                        handler(this, e);
                    }
                }
            }
        }

        #endregion

    }
}
